<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class CBase {	

    var $req = array();
    
    var $key = 'd83bv2a17d2m9d1a3j6k0j';
    
    var $CI = null;
    
    var $cache_time = 1200;
    
    var $user;
    /**
     * Constructor
     *
     * @access	public
     */
    public function __construct($p)
    {
        $this->initialize($p);
        $this->CI = & get_instance();
        $this->CI->load->driver('cache', array('adapter' => 'file'));
        $this->CI->load->model('m_Log');
    }

    private function initialize($p){
        if(isset($_POST['p'])){
            $this->req = json_decode($p['p'],true);
            if(!isset($this->req['MessageId'])) $this->req['MessageId']= '';
            if(!isset($this->req['Key'])) $this->req['Key']= '';
        }
        else
            $this->error ('Params Unavailable.');
    }

    // --------------------------------------------------------------------
    protected function validate_key(){
            return $this->req['Key'] == $this->key;
    }

    protected function error($msg){
        $this->show_msg($msg,NULL,0);
    }
	
    protected function show_msg($msg,$result=NULL,$success=1,$is_exit=TRUE){
        if(!isset($this->req['MessageId'])) $this->req['MessageId']= '';
        if(!isset($this->req['Key'])) $this->req['Key']= '';
        $res = array(
            'MessageId'	=> $this->req['MessageId'],
            'ACK' => $success,
            'Text'	=> $msg
        );
        if($result)$res['Result'] = $result;
        echo json_encode($res);
        if($is_exit)exit;
    }
    
    protected function  create_login_cache(){        
        $cache_key = md5('login_info_'.$this->user->user_id.'_'.time());
        $this->CI->cache->save($cache_key,$this->user,$this->cache_time);//20min
        return $cache_key;
    }
    
    protected function  valid_login($login_key){        
        if(isset($login_key)){            
            $this->user = $this->CI->cache->get($login_key);        
            if($this->user){//refresh cache
                $this->CI->cache->delete($login_key);
                $this->CI->cache->save($login_key,$this->user,$this->cache_time);
                return;
            }
        }
        
        $this->error('Login Valid Fail.');        
    }
}
